/*
 * Project Beknyou
 * Copyright (c) 2010-2011 Saint Paul College, All Rights Reserved
 * Redistributions in source code form must reproduce the above
 * Copyright and this condition.
 * The contents of this file are subject to the GNU General Public
 * License, Version 2 (the "License"); you may not use this file
 * except in compliance with the License. A copy of the License is
 * available at http://www.opensource.org/licenses/gpl-license.php.
 */
package com.benkyou.server;

import com.benkyou.server.listeners.PlayerMessageListener;
import com.benkyou.server.listeners.LoginServerListener;
import com.jme3.app.SimpleApplication;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.system.JmeContext;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.jme3.network.serializing.Serializer;
import com.benkyou.common.messages.*;
import com.benkyou.common.Player;
import com.benkyou.server.listeners.BenkyouClientConnectionListener;
import com.benkyou.server.listeners.ChatMessageListener;
import com.jme3.network.Filters;
import com.jme3.network.HostedConnection;
import java.util.ArrayList;

/**
 *
 * @author Austin Allman
 */
public class GameServer extends SimpleApplication {

    private Server myServer;
    private Thread webcamReader;
    //private ServerConsole serverConsole;
   // private Thread consoleThread;
    private String webcamURL = "http://199.17.224.254/axis-cgi/jpg/image.cgi?resolution=640x480";
    private ArrayList<Player> playerList;
   private VNCServer vncServer;
   private WebcamServer webcamServer;
    private int serverPort;
  

    public void setServerPort(int port){
        serverPort = port;
        
    }
    public static void main(String args[]) {
        GameServer app = new GameServer();
       
        if(args.length > 0){
            app.setServerPort(Integer.parseInt(args[0]));
        }
        
        try {
            app.start(JmeContext.Type.Headless);
        } catch (NoSuchMethodError e) {
        }
    }

    public void startWebcamServer() {
    }

    public GameServer() {
        super();
        Logger.getLogger("").setLevel(Level.SEVERE);
        Serializer.registerClass(WebcamMessage.class);
        Serializer.registerClass(VNCMessage.class);
        Serializer.registerClass(ChatClientMessage.class);
        Serializer.registerClass(LoginMessage.class);
        Serializer.registerClass(PlayerMessage.class);
        Serializer.registerClass(PlayerSyncMessage.class);
        Serializer.registerClass(PlayerDisconectMessage.class);
        serverPort = 6000;
        playerList = new ArrayList<Player>();
        //serverConsole = new ServerConsole(this);
        //consoleThread = new Thread(serverConsole);
       vncServer = new VNCServer(this);
        webcamServer = new WebcamServer(this);

        vncServer.setupBroadcaster();
        webcamServer.setupBroadcaster();
    }

    @Override
    public void simpleInitApp() {
        try {
            myServer = Network.createServer(serverPort);
            myServer.start();
            myServer.addMessageListener(new LoginServerListener(this), LoginMessage.class);
            myServer.addMessageListener(new ChatMessageListener(this), ChatClientMessage.class);
            myServer.addMessageListener(new PlayerMessageListener(this), PlayerMessage.class);
            myServer.addConnectionListener(new BenkyouClientConnectionListener(this));
           // consoleThread.start();
            System.out.println("Starting server on port " + serverPort);
          vncServer.startBroadcast();
        webcamServer.startBroadcast();
        } catch (IOException ex) {
            System.out.println(ex);
        }


    }

    @Override
    public void update() {
        super.update();
    }

    @Override
    public void destroy() {
        try {
            System.out.println("Sending message to clients... shutting down in 5 secounds....");
             getMyServer().broadcast(new ChatClientMessage("BenkyouServer","Server is shutting down in 5 secounds....."));
             Thread.sleep(5000l);
            super.destroy();
         //  vncServer.stopBroadcast();
           webcamServer.stopBroadcast();
            System.out.println("Closing Server");
            getMyServer().close();
            System.out.println("Shutting down console, Goodbye!");
            //onsoleThread.interrupt();
            System.exit(0);
        } catch (Exception e) {
        }
    }

    /**
     * @return the myServer
     */
    public Server getMyServer() {
        return myServer;
    }

    public String getWebcamURL() {
        return webcamURL;
    }

    public boolean login(String loginName, char[] password) {
       

        return true;
    }
    public  ArrayList<Player> getPlayerList(){
        return playerList;
    }
    public void syncPlayers(){
        System.out.println("Syncing players... curent number of connections :" + playerList.size());
        if(playerList.size() > 1){
            for(HostedConnection c :myServer.getConnections()){ 
              PlayerMessage[] players = new PlayerMessage[getPlayerList().size() - 1];
               ArrayList<Player> playerlist = getPlayerList();
               ArrayList<String> foundList = new ArrayList<String>();
               int playersCounter = 0;
               for(int i = 0; i < playerlist.size(); i ++){
                   String atriUUID =  c.getAttribute("UUID").toString();
                   if(!playerList.get(i).getUUID().equalsIgnoreCase(atriUUID)){
                       foundList.add(atriUUID);
                       System.out.println("Syncing player " + playerlist.get(i).getName() + playerlist.get(i).getID() + playerlist.get(i).getUUID());
                   players[playersCounter] = new PlayerMessage(playerlist.get(i).getName(), playerlist.get(i).getID(),playerlist.get(i).getUUID());
                   playersCounter++;
                   }
                  
               }

             
               getMyServer().broadcast(Filters.in(c), new PlayerSyncMessage(players));
               
               
            }
        }
    }
    public void  removePlayerByUUID(String uuid){
         ArrayList<Player> playerlist = getPlayerList();
               for(int i = 0; i < playerlist.size(); i ++){
                  if(playerlist.get(i).getUUID().equalsIgnoreCase(uuid)){
                      playerlist.remove(i);
                  }
               } 
    }
}
